<template>
  <div class="main">
    <!-- 文件表格 -->
    <el-table :data="sortedFiles" style="width: 100%">
      <el-table-column
        prop="filename"
        label="文件名"
        sortable
      ></el-table-column>
      <el-table-column prop="size" label="文件大小" sortable></el-table-column>
      <el-table-column prop="type" label="文件类型" sortable></el-table-column>
      <el-table-column
        prop="created_at"
        label="创建时间"
        sortable
      ></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <!-- 下载按钮 -->
          <el-button @click="downloadFile(row)" type="primary" size="small"
            >下载</el-button
          >
          <!-- 删除按钮 -->
          <el-button @click="deleteFile(row)" type="danger" size="small"
            >删除</el-button
          >
          <!-- 预览按钮 -->
          <el-button @click="scanFile(row)" type="primary" size="small"
            >预览</el-button
          >
          <!-- 分享按钮 -->
          <el-button @click="showShareDialog(row)" type="primary" size="small"
            >分享</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分享对话框 -->
    <ShareDialog
      v-model="shareDialogVisible"
      :file-info="shareFile"
      @success="handleShareSuccess"
    />
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { fileListApi, downloadApi, deleteApi } from "../utils/api";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import ShareDialog from "./ShareDialog.vue";
const router = useRouter();

// 定义响应式变量和排序状态
const files = ref([]);
const user_id = localStorage.getItem("id");
const shareDialogVisible = ref(false);
const shareFile = ref(null);
const sortKey = ref(null);
const sortOrder = ref("ascending");

// 初始化文件列表
const init = () => {
  fileListApi({ user_id }).then((res) => {
    res.forEach((item) => {
      item.created_at = item.created_at.replace("T", " ").split(".")[0];
    });
    files.value = res;
  });
};
init();

// 使用 Vuex store
const store = useStore();
// 监听 searchResult 状态的变化
store.watch(
  (state) => state.searchResult,
  (newVal) => {
    console.log("searchResult 变化了", newVal);
    const dataArray = [newVal];
    files.value = dataArray;
  }
);

// 计算属性，根据排序状态对文件进行排序
const sortedFiles = computed(() => {
  if (!sortKey.value) return files.value;

  const sorted = [...files.value];
  sorted.sort((a, b) => {
    let aValue = a[sortKey.value];
    let bValue = b[sortKey.value];

    // 日期排序的特殊情况
    if (sortKey.value === "created_at") {
      aValue = new Date(aValue).getTime();
      bValue = new Date(bValue).getTime();
    }

    if (sortOrder.value === "ascending") {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });

  return sorted;
});

// 下载文件操作
const downloadFile = (row) => {
  const id = row.id;
  const username = localStorage.getItem("username");

  downloadApi(username, { id }).then((res) => {
    const blob = new Blob([res], { type: row.type });
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = row.filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(link.href);
  }).catch((error) => {
    console.error('下载失败:', error);
    ElMessage.error('下载失败');
  });
};

// 删除文件操作
const deleteFile = (row) => {
  const confirmDelete = confirm(`确定删除文件 "${row.filename}" 吗？`);
  if (!confirmDelete) return;
  let id = row.id;
  deleteApi({ id }).then((res) => {
    console.log(res);
    init();
  });
};

// 预览文件操作
const scanFile = async (row) => {
  try {
    const id = row.id;
    const username = localStorage.getItem("username");

    if (row.type.startsWith("image")) {
      // 对于图片，直接使用静态文件URL
      const imageUrl = `http://192.168.31.222:3000/${username}/${row.relativeFilePath || row.filename}`;
      window.open(imageUrl, '_blank');
    } else if (row.type.startsWith("text")) {
      // 对于文本文件，下载后显示
      const downloadUrl = `http://192.168.31.222:3000/fileUploadDownload/download/${username}`;
      const response = await fetch(downloadUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id })
      });

      if (!response.ok) {
        throw new Error(`预览失败: ${response.status}`);
      }

      const text = await response.text();
      const newWindow = window.open('', '_blank');
      newWindow.document.write(`<pre>${text}</pre>`);
    } else {
      // 对于其他类型的文件，暂时不支持预览
      alert("不支持预览此类型的文件");
    }
  } catch (error) {
    console.error('预览文件失败:', error);
    alert(`预览失败: ${error.message}`);
  }
};

// 分享文件操作
const showShareDialog = (row) => {
  shareFile.value = row;
  shareDialogVisible.value = true;
};

// 分享成功回调
const handleShareSuccess = () => {
  // 刷新文件列表以更新分享状态
  init();
};
</script>

<style lang="less" scoped>
.main {
  margin-top: 10px;
}
</style>
